﻿using System;
using System.Web.UI;
using DeGiglio.biz.Twitter.Classes;
using webparts = DeGiglio.biz.Twitter.SharePoint.Webparts;

namespace DeGiglio.biz.Twitter.UserControls
{
    public partial class GetRateLimit : UserControl
    {
        #region " Properties "
        public webparts.GetRateLimit GetRateLimitWebPart { get; set; }
        #endregion

        #region " Controls "
        // The following controls appear here rather than using a .designer.cs file
        protected global::System.Web.UI.WebControls.Panel pnlErrors;
        protected global::System.Web.UI.WebControls.Panel pnlContent;
        protected global::System.Web.UI.WebControls.Label lblError;
        protected global::System.Web.UI.WebControls.Label lblTotalLimit;
        protected global::System.Web.UI.WebControls.Label lblRemainingLimit;
        protected global::System.Web.UI.WebControls.Label lblExpiration;
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if ((string.IsNullOrEmpty(this.GetRateLimitWebPart.TwitterConsumerKey)) ||
                (string.IsNullOrEmpty(this.GetRateLimitWebPart.TwitterConsumerSecret)))
            {
                lblError.Text = Common.GetResourceValue("ExceptionMessage_AuthNotSet", Common.LocaleID);
                SetPanels(true);
            }
            else
            {
                LoadRateInfo();
            }
        } // Page_Load

        private void LoadRateInfo()
        {
            try
            {
                TwitterHelper helper = new TwitterHelper(TwitterHelper.RequestType.GetRateLimit);

                helper.AuthenticateAs = TwitterHelper.AuthenticationType.Authenticated;
                helper.Twitter_ConsumerKey = this.GetRateLimitWebPart.TwitterConsumerKey;
                helper.Twitter_ConsumerSecret = this.GetRateLimitWebPart.TwitterConsumerSecret;

                RateLimit rateLimit = helper.GetRateLimit();
                lblTotalLimit.Text = rateLimit.Limit.ToString();
                lblRemainingLimit.Text = rateLimit.RemainingLimit.ToString();
                lblExpiration.Text = rateLimit.ResetTime.ToString();
                SetPanels(false);
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
                SetPanels(true);
            }
        } // LoadRateInfo

        private void SetPanels(bool isError)
        {
            pnlContent.Visible = !isError;
            pnlErrors.Visible = isError;
        } // SetPanels
    }
}
